package com.example.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/** 请求拦截器
 *  filterName表示给该程序起一个别名
 *  value表示拦截路径
 * @author YAO
 * @create 2021-05-13 14:47
 */
public class AdminFilter implements Filter {

    public AdminFilter() {
        System.out.println("1.构造器方法");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("2.init初始化方法");

//        1、获取 Filter 的名称 filter-name 的内容
        System.out.println("filter-name的值是：" + filterConfig.getFilterName());
//        2、获取在 web.xml 中配置的 init-param 初始化参数
        System.out.println("初始化参数username的值是：" + filterConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是：" + filterConfig.getInitParameter("url"));
//        3、获取 ServletContext 对象
        System.out.println(filterConfig.getServletContext());
    }

    /**
     * 专门用于拦截请求,可以做权限检查
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("3.doFilter请求拦截方法");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();

        Object user = session.getAttribute("user");

        //如果==null说明没有登录
        if(user == null){
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }else {
            //让程序继续往下访问用户的目标资源，即放行
            chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {
        System.out.println("4.销毁方法");

    }
}
